//
//  BloodOxygenChartView.swift
//  DaRings
//
//  Created by 易先生 on 2022/11/2.
//

import UIKit
import MYModule
import Charts

 open class SevenTimeBarChartView: View {
     
     private let barHeight: CGFloat = 150.0
     
     
     open var barModel: BarsModel? {
         
         didSet {
             
             let barModel = barModel ?? BarsModel(color: .clear, hightLightColor: .clear, bars: [], xAxisValueFormatter: DefaultValueFormatter() as! IAxisValueFormatter, xConfig: DFBarChartViewConfig())
             
             let datas = barModel.bars.map { Double($0.data) }
             
             let times = barModel.bars.map { model ->String in
                 
                 if model.time == 0 || model.data == 0 {
                     return ""
                 }
                 return Date(timeIntervalSince1970: model.time).localStringOfDateTime
             }
             
             
             barChartView.layoutIfNeeded()
             markView.layoutIfNeeded()
             
             // 给markView 留显示位置
             var maxValue: Double = 0
             
             var dataYMaxValue: Double = 0
             var dataYminValue: Double = 0
             barModel.bars.forEach {
                 dataYMaxValue = Swift.max(dataYMaxValue, $0.data)
                 dataYminValue = Swift.min(dataYminValue, $0.data)
             }
             let markViewHeight = markView.frame.size.height + markView.offset.y
             let mut = markViewHeight/barHeight
             let dataMut = dataYminValue/dataYMaxValue
             
             if dataMut < mut { // 数据太接近了, 以最大值 + 比例 得出Y轴最大值
                 maxValue = dataYMaxValue * (1.0 + mut)
                 
             } else {
                 
                 // 以手动填入的为最大值
                 if let yMaxValue = barModel.YMaxValue {
                     maxValue = yMaxValue
                 }
             }
             
             markView.timeDatas = times
             markView.textBgColor = barModel.hightLightColor
             
             let heightDiff = markViewHeight * mut
             let hasSetYMaxValue = (heightDiff > markViewHeight && maxValue > 0)
             // 高度够才设置最大值都合适
             if hasSetYMaxValue {
                 barChartView.setYMax(value: maxValue)
             } else {
                 
                 print("markView 显示有干涉")
                 print("可能是数据太接近了，也可能是高度不够")
             }
             
             barChartView.setConfig(barModel.xConfig)
             barChartView.setXAxis(valueFormatter: barModel.xAxisValueFormatter)
             barChartView.setBarCount(7)
             barChartView.setData(datas,
                                  barColor: barModel.color,
                                  barHighLichtColor:  barModel.hightLightColor, showEmpty: true)
             
         }
    
     }
    
    
     open override func makeUI() {
        super.makeUI()
        
        self.addSubview(titleLabel)
        self.addSubview(barChartView)
        
        barChartView.setMarkerView(self.markView)
        
        markView.snp.makeConstraints { make in
            make.height.equalTo(20)
        }

        titleLabel.snp.makeConstraints { make in
            make.top.equalToSuperview().offset(15)
            make.leading.equalToSuperview().offset(20)
            make.trailing.equalToSuperview().offset(-20)
        }
        
        barChartView.snp.makeConstraints { make in
            make.top.equalTo(titleLabel.snp.bottom).offset(15)
            make.leading.equalToSuperview()
            make.trailing.equalToSuperview()
            make.height.equalTo(barHeight)
            make.bottom.equalToSuperview().offset(-20)
        }
    }
     
     

    public lazy var titleLabel: Label = {
        let titleLabel = Label()
        titleLabel.textColor = UIColor.assist_222222
        titleLabel.font = Fonts.boldSystemFont(ofSize: 14)
        titleLabel.text = "heart_rate_last_seven_times_record_title".language
        titleLabel.numberOfLines = 0
        return titleLabel
    }()
    
    public lazy var barChartView: DFBarChartView = {
        let barChartView = DFBarChartView()
        
        return barChartView
    }()
    
    public let markView = DataTimeShowMarkerView()

}


extension SevenTimeBarChartView {
    
    public struct BarValue {
        
        /// 时间戳
        public var time: Double
        /// 数据
        public var data: Double
        
    }
    
    public class BarsModel: NSObject {
        
        /// 普通颜色
        public var color: UIColor
        
        /// 高亮颜色
        public var hightLightColor: UIColor
        
        /// data 数据
        public var bars: [BarValue]
        
        /// x轴格式
        public var xAxisValueFormatter: IAxisValueFormatter
        
        /// x 轴颜色字体大小等设置
        public var xConfig: DFBarChartViewConfig
        
        /// Y 轴 手动最大值
        public var YMaxValue: Double?
        
        /// 初始化model
        /// - Parameters:
        ///   - color: 颜色
        ///   - hightLightColor: 高亮
        ///   - bars: 数据源
        ///   - yValue: Y 轴最大值，如果传 nil 将从bars自动计算出来
        public init(color: UIColor, hightLightColor: UIColor, bars: [BarValue], xAxisValueFormatter: IAxisValueFormatter, xConfig: DFBarChartViewConfig, YMaxValue: Double? = nil) {
            
        
            self.color = color
            self.hightLightColor = hightLightColor
            self.bars = bars
            self.xAxisValueFormatter = xAxisValueFormatter
            
            var isEmpty: Bool = true
            bars.forEach {
                
                if $0.data > 0 {
                    isEmpty = false
                }
            }
            
            var config = xConfig
            if isEmpty {
                config.xAxisLabelTextColor = .clear
            }
            self.xConfig = config
            
            super.init()
            
            self.YMaxValue = YMaxValue
            
        }
        
    }
    
}
